import store from '@/store'
import { h } from 'vue'
import { createRouter, createWebHashHistory, RouterView } from 'vue-router'
const routes = [
  {
    path: '/', name: 'xtx-layout', component: () => import('@/views/Layout'),
    children: [
      {
        path: '', component: () => import('@/views/home/index')
      },
      {
        path: 'category/:id',
        component: () => import('@/views/category/index')
      },
      {
        path: 'category/sub/:id',
        component: () => import('@/views/category/sub'),
      },
      {
        path: '/product/:id',
        component: () => import('@/views/goods/index')
      },
      {
        path: '/cart',
        component: () => import('@/views/cart/index')
      },
      {
        path: '/member/checkout',
        component: () => import('@/views/member/pay/checkout')
      },
      {
        path: '/member/pay',
        component: () => import('@/views/member/pay/index')
      },
      {
        path: '/pay/callback',
        component: () => import('@/views/member/pay/components/result')
      },
      {
        path: '/member',
        component: () => import('@/views/member/Layout'),
        children: [
          {
            path: '/member',
            component: () => import('@/views/member/home/index')
          },
          {
            path: '/member/order',
            // vue3.0 需要有嵌套关系才能模糊匹配    
            component: {
              render: () => h(<RouterView />)

            },
            children: [{
              path: '',
              component: () => import('@/views/member/order')
            },
            {
              path: ':id',
              component: () => import('@/views/member/order/detail')
            }]
          }
        ]
      }
    ]
  },
  {
    path: '/login', name: 'login', component: () => import('@/views/login')
  },
  {
    path: '/login/callback', name: 'loginCallback', component: () => import('@/views/login/callback')
  }

]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior() { // 每次切换滚动到顶部
    return { left: 0, top: 0 }
  }
})

// 前置导航守卫
router.beforeEach((to, from, next) => {
  // 用户信息
  const { token } = store.state.user.profile;
  // 跳转去member开头的地址却没有登录
  if (to.path.startsWith('/member') && !token) {
    return next('/login?redirectUrl=' + encodeURIComponent(to.fullPath))
  }
  next();
})
export default router
